﻿namespace DataMorph.Web
{
    using System.Web.Http;
    using System.Web.Http.Dispatcher;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;

    using DataMorph.Common;
    using DataMorph.Common.DataAccess;
    using DataMorph.Common.Storage;
    using DataMorph.Processing;
    using DataMorph.Web.App_Start;
    using DataMorph.Web.Endpoints;
    using DataMorph.Web.Services;

    using Microsoft.Practices.Unity;
    using Microsoft.WindowsAzure;
    using Microsoft.WindowsAzure.Storage;

    public class WebApiApplication : System.Web.HttpApplication
    {
        private readonly IUnityContainer container;

        public WebApiApplication()
        {
            this.container = new UnityContainer();

            this.container.RegisterType<INotifier, Notifier>()
                          .RegisterType<ICloudStorageAccount, CloudStorageAccountWrapper>(
                                                                    new ContainerControlledLifetimeManager(), 
                                                                    new InjectionConstructor(
                                                                                CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("DataMorph.StorageAccount"))))
                          .RegisterType<IDataAccess, DataAccess>(new ContainerControlledLifetimeManager())
                          .RegisterType<IWorkQueue, WorkQueue>(new ContainerControlledLifetimeManager())
                          .RegisterType<IProgressQueue, ProgressQueue>(new ContainerControlledLifetimeManager())
                          .RegisterType<IDataMorphService, DataMorphService>(new ContainerControlledLifetimeManager());
        }

        public override void Dispose()
        {
            this.container.Dispose();
            base.Dispose();
        }

        protected void Application_Start()
        {
            GlobalConfiguration.Configuration.Services.Replace(
                typeof(IHttpControllerActivator), new CompositionRoot(this.container));

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            BundleConfig.RegisterBundles(BundleTable.Bundles);

            RouteTable.Routes.MapConnection<DataGeneratorEndpoint>("generator", "/generator");
            RouteTable.Routes.MapHubs();

            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}